package com.like.fragment;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.like.adapter.ExpertsListViewAdapter;
import com.like.entity.Department;
import com.like.entity.DocListReq;
import com.like.entity.DocListResp;
import com.like.entity.EventWrapper;
import com.like.entity.GeneralResponse;
import com.like.entity.GetDepResp;
import com.like.hospitalworld.MainActivity;
import com.like.hospitalworld.R;
import com.like.hospitalworld.SubjectActivity;
import com.like.likeutils.network.RetrofitCallback;
import com.like.network.RetrofitUtil;
import com.like.network.WindowService;
import com.like.utils.Constants;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import retrofit2.Call;
import retrofit2.Response;

@ContentView(R.layout.fragment_main_window)
public class MainWindowFragment extends BaseFragment {

    public static final int REQUEST_COURSE_INDEX_CHANGE = 100;

    @ViewInject(R.id.window_list)
    private PullToRefreshListView mListView;
    @ViewInject(R.id.title)
    private TextView mTitle;

    private ExpertsListViewAdapter mDocAdapter;
    private MainActivity mMainActivity;
    private WindowService mWindowService;
    private int mType = 0;
    private Department mCurrentDep;
    private int mPageCount = 15;
    private int mCurrentPage = 0;

    @Override
    protected void onCreateView() {
        super.onCreateView();
        setToolbar();
        initList();
        mWindowService = RetrofitUtil.getService(WindowService.class);
        getDocList(false);
        mCurrentDep = m.getCurrentDep();
        EventBus.getDefault().register(this);
    }

    private void initList() {
        mListView.setMode(PullToRefreshBase.Mode.BOTH);
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                mCurrentPage = 0;
                getDocList(false);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                mCurrentPage += 1;
                getDocList(true);
            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (getActivity() instanceof MainActivity)
            mMainActivity = (MainActivity) getActivity();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            setToolbar();
            Department currentDep = m.getCurrentDep();
            if (currentDep != null && mCurrentDep != null) {
                if (currentDep.id != mCurrentDep.id) {
                    mCurrentPage = 0;
                    getDocList(false);
                    mCurrentDep = m.getCurrentDep();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onGetEvent(EventWrapper event) {
        if (EventWrapper.isMatch(event, getClass(), REQUEST_COURSE_INDEX_CHANGE)) {
            mCurrentPage = 0;
            getDocList(false);
        }
    }

    private void getDocList(final boolean append) {
        Department dep = m.getCurrentDep();
        if (dep != null) {
            if (mDocAdapter == null)
                mType = dep.subDeps.get(1).subDeps.get(0).id;
            else
                mType = dep.subDeps.get(1).subDeps.get(mDocAdapter.getCourseIndex()).id;
        }
        DocListReq req = new DocListReq(mType, mCurrentPage, mPageCount);
        Call<GeneralResponse<DocListResp>> call = mWindowService.getDocList(Constants.getGUID(), m.getToken(), req);
        call.enqueue(new RetrofitCallback<GeneralResponse<DocListResp>>() {
            @Override
            public void onResponse(Call<GeneralResponse<DocListResp>> call, Response<GeneralResponse<DocListResp>> response) {
                mListView.onRefreshComplete();
                if (!response.isSuccessful())
                    return;
                GeneralResponse<DocListResp> resp = response.body();
                DocListResp docListResp = resp.data;
                List<DocListResp.Doctor> docs = docListResp.doctorList;
                if (mDocAdapter == null) {
                    mDocAdapter = new ExpertsListViewAdapter(m.mContext, docs, m);
                    mListView.setAdapter(mDocAdapter);
                } else
                    mDocAdapter.update(docs, append);
            }

            @Override
            public void onFailure(Call<GeneralResponse<DocListResp>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private void setToolbar() {
        View v = mMainActivity.setToolbar(R.layout.toolbar_window);
        x.view().inject(this, v);
        Department dep = m.getCurrentDep();
        if (dep != null && mTitle != null)
            mTitle.setText(dep.name + "医界之窗");
    }

    @Event(value = R.id.window_list, type = AdapterView.OnItemClickListener.class)
    private void itemClick(AdapterView<?> parent, View view, int position, long id) {
        position -= 1;
        DocListResp.Doctor doctor = mDocAdapter.getItem(position);
        if (doctor == null)
            return;
        EventBus.getDefault().postSticky(new EventWrapper(doctor, SubjectActivity.class, SubjectActivity.REQUEST_DOCTOR_INFO));
        Intent intent = new Intent(getActivity(), SubjectActivity.class);
        startActivity(intent);
    }
}
